import React, { useEffect, useRef } from "react";
import axios from "axios";
interface PropsType {
  children: JSX.Element;
  // 发送前 验证函数  返回值为真  才继续执行上传， 返回值为假 不上传
  beforeUpload: (file: File) => Boolean | undefined;
  upload: (file: File) => void;
}

export const Upload: React.FC<PropsType> = ({
  children,
  beforeUpload,
  upload,
}) => {
  const ipt = useRef<HTMLInputElement | null>(null);
  const wrapper = useRef<HTMLDivElement | null>(null);
  const handleChange = () => {
    if (ipt.current && ipt.current.files) {
      const file = ipt.current.files[0];
      beforeUpload(file) && upload(file);
    }
  };

  useEffect(() => {
    const dragover = (e: DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
    };
    if (wrapper.current) {
      // 拖拽元素 在目标元素 松手
      wrapper.current.addEventListener("drop", (e) => {
        const file = e.dataTransfer?.files[0] as File;
        beforeUpload(file) && upload(file);
      });
    }

    // 阻止浏览器默认的拖放行为
    document.addEventListener("dragover", dragover);
    document.addEventListener("drop", dragover);
    return () => {
      document.removeEventListener("dragover", dragover);
      document.addEventListener("drop", dragover);
    };
  }, []);

  return (
    <div ref={wrapper}>
      <input
        ref={ipt}
        type="file"
        style={{ display: "none" }}
        onChange={() => handleChange()}
      />
      <div onClick={() => ipt.current && ipt.current.click()}>{children}</div>
    </div>
  );
};
